package com.huan.study.skywalking.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.skywalking.apm.toolkit.trace.ActiveSpan;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 上报 Get 请求参数到 SkyWalking 中
 *
 * @author huan.fu 2020/7/9 - 18:35
 */
@WebFilter(urlPatterns = "/*", filterName = "reportRequestParam2SkyWalkingFilter")
public class ReportRequestParam2SkyWalkingFilter extends OncePerRequestFilter {
    private static final Logger log = LoggerFactory.getLogger(ReportRequestParam2SkyWalkingFilter.class);

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        log.info("current request uri:[{}]", request.getRequestURI());
        reportRequestParam(request);
        chain.doFilter(request, response);
    }

    @Trace(operationName = "拦截 GET 参数")
    private void reportRequestParam(HttpServletRequest request) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (!CollectionUtils.isEmpty(parameterMap)) {
                ActiveSpan.info("我是一个自定义的消息");
                ActiveSpan.tag("Request Uri", request.getRequestURI());
                ActiveSpan.tag("Request Param", OBJECT_MAPPER.writeValueAsString(parameterMap));
            }
        } catch (Exception e) {
            log.info("report request param to SkyWalking error:[{}].", e.getMessage());
        }
    }
}
